# TODO: 导入必要的库和模块
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import StandardScaler
import pickle
# TODO: 加载数字数据集
digits = datasets.load_digits()   
# TODO: 将数据集划分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target, test_size=0.2, random_state=42)
# TODO: 初始化变量以存储最佳准确率，相应的k值和最佳knn模型
best_k = 0
best_accuracy = 0.0
k_values = range(1, 41)
accuracies = []

for k in k_values:
    knn = KNeighborsClassifier(n_neighbors=k)
    knn.fit(X_train, y_train)
    y_pred = knn.predict(X_test)
    accuracy = accuracy_score(y_test, y_pred)
    accuracies.append(accuracy)
    if accuracy > best_accuracy:
        best_k = k
        best_accuracy = accuracy



# TODO: 初始化一个列表以存储每个k值的准确率

# TODO: 尝试从1到40的k值，对于每个k值，训练knn模型，保存最佳准确率，k值和knn模型
best_k = k_values[accuracies.index(max(accuracies))]
print(f"Best K value: {best_k}")
print(f"Best Accuracy: {best_accuracy:.4f}")
# TODO: 将最佳KNN模型保存到二进制文件

with open('best_knn_model.pkl', 'wb') as file:
    pickle.dump(knn, file)
# TODO: 打印最佳准确率和相应的k值
plt.figure(figsize=(10, 6))
plt.plot(k_values, accuracies, marker='o', linestyle='-', color='b')
plt.title('KNN Varying number of neighbors')
plt.xlabel('Number of neighbors')
plt.ylabel('Accuracy')
plt.xticks(k_values)

# 添加垂直线
plt.axvline(x=best_k, color='red', linestyle='--', label=f'Best K={best_k}')

# 添加图例
plt.legend()
#保存图像
plt.savefig('accuracy_plot.pdf', format='pdf')
# 显示图像
plt.show()